package com.example.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.enums.RoleEnum;
import com.example.entity.Department;
import com.example.entity.Employee;
import com.example.entity.Leaves;
import com.example.entity.Meeting;
import com.example.mapper.EmployeeMapper;
import com.example.mapper.LeavesMapper;
import com.example.service.EmployeeService;
import com.example.service.LeavesService;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
@Service
public class LeaveServiceImpl extends ServiceImpl<LeavesMapper,Leaves> implements LeavesService {

    @Autowired
    private EmployeeService employeeService;


    @Autowired
    private LeavesMapper leavesMapper;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public void add(Leaves leaves) {
        Employee user = TokenUtils.getCurrentUser();
        leaves.setCreateId(user.getId());
        leaves.setStatus("未处理");
        if (user.getRole().equals(RoleEnum.USER.name())){
            // 获取到当前部门的主管
            Employee departmentRole = employeeService.selectByDepartmentIdAndRole(user.getDepartmentId(), RoleEnum.DEPARTMENT_MANAGER.name());
            leaves.setExamineId(departmentRole.getId());
        }else if (user.getRole().equals(RoleEnum.DEPARTMENT_MANAGER.name())){
            Employee departmentManger = employeeService.selectByDepartmentIdAndRole(0, RoleEnum.GENERAL_MANAGER.name());
            leaves.setExamineId(departmentManger.getId());
        }
        leavesMapper.insert(leaves);
    }

    @Override
    public void deleteById(Integer id) {
        leavesMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {

    }

    @Override
    public void updateLeave(Leaves leaves) {
        leavesMapper.updateById(leaves);
    }

    @Override
    public Leaves selectById(Integer id) {
        return null;
    }

    @Override
    public List<Leaves> selectAll(Leaves leaves) {
        LambdaQueryWrapper<Leaves> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Employee user = TokenUtils.getCurrentUser();
        // 判断是不是普通用户
        if (user.getRole().equals(RoleEnum.USER.name())) {
            lambdaQueryWrapper.eq(Leaves::getCreateId,user.getId());
        }
        // 判断当前用户是不是部门主管
        if (user.getRole().equals(RoleEnum.DEPARTMENT_MANAGER.name())) {
            lambdaQueryWrapper.and( wq ->{wq
                    .eq(Leaves::getCreateId,user.getId())
                    .or()
                    .eq(Leaves::getExamineId,user.getId());
            });
        }
        //判断用户是否是总经理
        if (user.getRole().equals(RoleEnum.GENERAL_MANAGER.name())){
            lambdaQueryWrapper.eq(Leaves::getExamineId,user.getId());
        }
        // 根据前端返回的名字查询对应的id
        if (StringUtils.isNotBlank(leaves.getCreatorName())) {
            QueryWrapper<Employee> nameQueryWrapper = new QueryWrapper<>();
            nameQueryWrapper.eq("name", leaves.getCreatorName());
            Employee employee = employeeMapper.selectOne(nameQueryWrapper);

            // 如果查询到了对应的记录，则根据id进行最终的查询
            if (employee != null) {
                lambdaQueryWrapper.eq(Leaves::getCreateId, employee.getId());
            }
            else {
                return null;
            }

        }
        List<Leaves> list = leavesMapper.selectList(lambdaQueryWrapper);
        list.forEach( item ->{
            // 计算开始时间和结束时间的时间差
            long days = ChronoUnit.DAYS.between(item.getBeginTime(), item.getEndTime());
            // 返回请假的天数
            item.setDay(days);
            // 获取处理人id
            Integer examineId = item.getExamineId();
            // 获取创建人id
            Integer createId = item.getCreateId();
            // 根据创建者id去员工表搜索创建者的名字
            item.setCreatorName(employeeService.selectById(createId).getName());
            // 根据请假表中的处理人id查找到部门的主管的名字
            item.setExamineName(employeeService.selectById(examineId).getName());
        });
        return list;
    }

    @Override
    public PageInfo<Leaves> selectPage(Leaves leaves, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Leaves> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Employee user = TokenUtils.getCurrentUser();
        // 判断是不是普通用户
        if (user.getRole().equals(RoleEnum.USER.name())) {
            lambdaQueryWrapper.eq(Leaves::getCreateId,user.getId());
        }
        // 判断当前用户是不是部门主管
        if (user.getRole().equals(RoleEnum.DEPARTMENT_MANAGER.name())) {
            lambdaQueryWrapper.and( wq ->{wq
                    .eq(Leaves::getCreateId,user.getId())
                    .or()
                    .eq(Leaves::getExamineId,user.getId());
            });
        }
        //判断用户是否是总经理
        if (user.getRole().equals(RoleEnum.GENERAL_MANAGER.name())){
            lambdaQueryWrapper.eq(Leaves::getExamineId,user.getId());
        }
        // 根据前端返回的名字查询对应的id
        if (StringUtils.isNotBlank(leaves.getCreatorName())) {
            QueryWrapper<Employee> nameQueryWrapper = new QueryWrapper<>();
            nameQueryWrapper.eq("name", leaves.getCreatorName());
            Employee employee = employeeMapper.selectOne(nameQueryWrapper);

            // 如果查询到了对应的记录，则根据id进行最终的查询
            if (employee != null) {
                lambdaQueryWrapper.eq(Leaves::getCreateId, employee.getId());
            }
            else {
                return null;
            }

        }
        lambdaQueryWrapper.orderByDesc(Leaves::getId);
        PageHelper.startPage(pageNum, pageSize);
        List<Leaves> list = leavesMapper.selectList(lambdaQueryWrapper);
        list.forEach( item ->{
            // 计算开始时间和结束时间的时间差
            long days = ChronoUnit.DAYS.between(item.getBeginTime(), item.getEndTime());
            // 返回请假的天数
            item.setDay(days);
            // 获取处理人id
            Integer examineId = item.getExamineId();
            // 获取创建人id
            Integer createId = item.getCreateId();
            // 根据创建者id去员工表搜索创建者的名字
            item.setCreatorName(employeeService.selectById(createId).getName());
            // 根据请假表中的处理人id查找到部门的主管的名字
            item.setExamineName(employeeService.selectById(examineId).getName());
        });
        return PageInfo.of(list);
    }

    @Override
    public Leaves queryIsLeaves(Integer id, LocalDateTime time) {
       return leavesMapper.queryIsLeaves(id, time);
    }
}
